package com.changcheng.project.yuminsi.converter;

import com.changcheng.project.yuminsi.error.GlobalErrorCode;
import com.changcheng.project.yuminsi.vo.BaseOutput;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Collection;

/**
 * Web Response Result 返回封装
 * <p>
 * <p>
 * 参考：AbstractJackson2HttpMessageConverter
 * </p>
 *
 * @description
 * @author: zuesgooogle
 * @date: 2018/3/7 下午10:26
 */
public class Jackson2HttpMessageConverter extends AbstractJackson2HttpMessageConverter {
    /**
     * swagger-ui.html 访问结果格式化
     */
    public static final String EXCLUDE = "springfox.documentation";

    public Jackson2HttpMessageConverter() {
        this(Jackson2ObjectMapperBuilder.json()
                .featuresToEnable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL)
                .build());
    }

    public Jackson2HttpMessageConverter(ObjectMapper objectMapper) {
        super(objectMapper, MediaType.APPLICATION_JSON, new MediaType("application", "*+json"));
//        super(objectMapper, MediaType.ALL);
    }

    @Override
    protected void writeInternal(Object object, Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        if (object instanceof BaseOutput || object.getClass().getName().contains(EXCLUDE)) {
            super.writeInternal(object, type, outputMessage);
            return;
        }

        if (object instanceof Collection) {
            Collection<?> col = (Collection<?>) object;
            if (col.iterator().hasNext()) {
                if (col.iterator().next().getClass().getName().contains(EXCLUDE)) {
                    super.writeInternal(object, type, outputMessage);
                    return;
                }
            }
        }
        super.writeInternal(BaseOutput.responseData(GlobalErrorCode.SUCCESS, object), type, outputMessage);
    }

//    @Override
//    public boolean canWrite(Type type, Class<?> contextClass, MediaType mediaType) {
//        if (mediaType == null
//                || MediaType.IMAGE_JPEG.includes(mediaType)
//                || MediaType.IMAGE_PNG.includes(mediaType)
//                || MediaType.IMAGE_GIF.includes(mediaType)
//                || MediaType.APPLICATION_PDF.includes(mediaType)
//                || MediaType.APPLICATION_OCTET_STREAM.includes(mediaType)
//        ) {
//            return false;
//        }
//        return super.canWrite(type, contextClass, mediaType);
//    }


}
